package com.hailiang.study.javase.java.util.stream;

import com.hailiang.study.javase.java.util.stream.vo.Student;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

public class Collectors_collectionAndThen {

    /**
     * 多级分组
     *      先按性别分组，然后按是否及格分组
     */
    @Test
    public void testMultiGroupByAndCollectingAndThen() {
        List<Student> students = Arrays.asList(
                new Student(1, 19, "张三", "M", true),
                new Student(1, 33, "张三", "M", true),
                new Student(2, 18, "李四", "M", false),
                new Student(3, 21, "王五", "F", true),
                new Student(4, 20, "赵六", "F", false)
        );

        // 1. 根据性别(sex)分组
        // 2. 将根据性别(sex)分组后的结果，再次根据isPass分组
        // 3. 将第2步分组的结果，进行收集（根据年龄的最大值进进行收集），收集的结果取为Student
        Map<String, Map<Boolean, Student>> result
                = students.stream().collect(
                        Collectors.groupingBy(
                                Student::getSex,
                                Collectors.groupingBy(
                                        Student::isPass,
                                        Collectors.collectingAndThen(
                                                Collectors.maxBy(Comparator.comparing(Student::getAge)),
                                                Optional::get
                                        )
                                )
                        )
                );
        System.out.println(result);
    }
}
